/*
 * @Description:设备信息
 * @Author: ldx
 * @Date: 2022-09-18 22:35:41
 * @LastEditors: ldx
 * @LastEditTime: 2022-09-29 23:44:04
 */
import {
  MinusCircleOutlined,
  PlusOutlined,
  UploadOutlined
} from '@ant-design/icons'
import { useAntdTable, useRequest } from 'ahooks'
import {
  Button,
  Col,
  Form,
  Input,
  message,
  Modal,
  Popconfirm,
  Row,
  Table,
  Upload
} from 'antd'
const { TextArea } = Input
import moment from 'moment'
import { useState } from 'react'

import {
  createEquip,
  deleteEquip,
  downloadEquip,
  queryDetails,
  queryEquip,
  updateEquip
} from '@/api/database/equip'
import { TextTooltip } from '@/components'
import AuthButton from '@/components/authButton'
import { PageContainer } from '@/components/pageContainer'
const Equip = () => {
  const [form] = Form.useForm()
  const [addForm] = Form.useForm()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isModalOpenDetails, setIsModalOpenDetails] = useState(false)
  const [details, setDetails] = useState<any>()
  /** 设备信息列表 */
  const { tableProps, search } = useAntdTable(queryEquip, {
    form
  })

  /** 设备信息详情 */
  const { runAsync: runQueryDetails } = useRequest(queryDetails, {
    manual: true,
    onSuccess: (res) => {
      setDetails(res.data)
    }
  })
  /** 设备信息删除 */
  const { runAsync: runDeleteEquip } = useRequest(deleteEquip, {
    manual: true,
    onSuccess: () => {
      search.submit()
    }
  })
  /** 设备信息下载 */
  const { runAsync: runDownloadEquip } = useRequest(downloadEquip, {
    manual: true,
    onSuccess: (res) => {
      console.log('res', res)
      const filename = res.headers['content-disposition']
        .split(';')[1]
        .split('=')[1]
      // 创建隐藏的可下载链接
      const eleLink = document.createElement('a')
      eleLink.download = decodeURIComponent(filename)
      eleLink.style.display = 'none'
      // 字符内容转变成blob地址
      const blob = new Blob([res.data])
      eleLink.href = URL.createObjectURL(blob)
      // 触发点击
      document.body.appendChild(eleLink)
      eleLink.click()
      // 然后移除
      document.body.removeChild(eleLink)
    }
  })
  /** 创建设备信息 */
  const { runAsync: runCreateEquip } = useRequest(createEquip, {
    manual: true,
    onSuccess: () => {
      search.reset()
      setIsModalOpen(false)
      addForm.resetFields()
      message.success('创建成功')
      setDetails(undefined)
    }
  })
  /** 更新设备信息 */
  const { runAsync: runUpdateEquip } = useRequest(updateEquip, {
    manual: true,
    onSuccess: () => {
      search.reset()
      setIsModalOpen(false)
      addForm.resetFields()
      message.success('更新成功')
      setDetails(undefined)
    }
  })
  const columns: any[] = [
    {
      title: '序号',
      width: 60,
      align: 'center',
      dataIndex: 'a',
      render: (text: string, record: any, index: number) => {
        return <span>{index + 1}</span>
      }
    },
    {
      title: '设备名称',
      align: 'center',
      dataIndex: 'equipName'
    },
    // {
    //   title: '摘要',
    //   align: 'center',
    //   ellipsis: true,
    //   dataIndex: 'description'
    // },
    {
      title: '文件名称',
      align: 'center',
      ellipsis: true,
      dataIndex: 'fileName'
    },
    {
      title: '文件路径',
      align: 'center',
      ellipsis: true,
      dataIndex: 'filePath'
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
      render: (text: string) => {
        return <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
      }
    },
    {
      title: '创建人',
      align: 'center',
      dataIndex: 'creatorName'
    },
    {
      title: '操作',
      width: 300,
      align: 'center',
      key: 'action',
      render: (text: number, record: any) => (
        <div>
          <AuthButton
            auth={['/**', '/equip/**', '/equip/details/{id}']}
            type="link"
            onClick={() => {
              setIsModalOpenDetails(true)
              runQueryDetails(record.id)
            }}
          >
            详情
          </AuthButton>
          <Popconfirm
            title="确认下载?"
            onConfirm={() => runDownloadEquip(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <AuthButton
              auth={['/**', '/equip/**', '/equip/download/{id}']}
              type="link"
            >
              下载
            </AuthButton>
          </Popconfirm>
          <AuthButton
            type="link"
            auth={['/**', '/equip/**', '/equip/update']}
            onClick={() => {
              // setRole(record)
              runQueryDetails(record.id).then((res) => {
                addForm.setFieldsValue(res.data)
                setIsModalOpen(true)
                // setDetails(record)
              })
            }}
          >
            编辑
          </AuthButton>

          <Popconfirm
            title="确认删除设备资料?"
            onConfirm={() => runDeleteEquip(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <AuthButton
              auth={['/**', '/equip/**', '/equip/delete/{id}']}
              type="link"
            >
              删除
            </AuthButton>
          </Popconfirm>
        </div>
      )
    }
  ]
  return (
    <>
      <PageContainer>
        <div>
          <Form form={form}>
            <Row gutter={24}>
              <Col span={5}>
                <Form.Item name="keyword">
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Button onClick={() => search.submit()} type="primary">
                  搜索
                </Button>
              </Col>
              <Col span={11} className="flex justify-end">
                <AuthButton
                  auth={['/**', '/equip/**', '/equip/create']}
                  onClick={() => setIsModalOpen(true)}
                  type="primary"
                >
                  创建
                </AuthButton>
              </Col>
            </Row>
          </Form>
          <Table
            columns={columns}
            scroll={{ x: 1400 }}
            rowKey={(record) => record.id}
            {...tableProps}
            pagination={{
              showTotal: (total, range) => {
                console.log('xxx', range)
                const num = Math.ceil(total / 10)
                return (
                  <span style={{ color: '#fff', marginRight: '10px' }}>
                    共{num}页/共{total}条结果
                  </span>
                )
              },
              ...tableProps.pagination
            }}
          />
        </div>
      </PageContainer>
      <Modal
        width={800}
        title="设备资料详情"
        visible={isModalOpenDetails}
        onOk={() => {
          setIsModalOpenDetails(false)
          setDetails(undefined)
        }}
        onCancel={() => {
          setIsModalOpenDetails(false)
          setDetails(undefined)
        }}
      >
        <div className="pl-20px details">
          <div>
            <span className="w-120px inline-block "></span>
            <span className="520px flex justify-center">
              <img
                style={{ width: '160px', height: '160px' }}
                src={`${window.location.origin}${details?.imgUri}`}
                alt=""
              />
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">设备名称：</span>
            <span>{details?.equipName}</span>
          </div>
          {/* <div>
            <span className="w-120px inline-block ">摘要：</span>
            <span>
              <TextTooltip className="w-520px">
                {details?.description}
              </TextTooltip>{' '}
            </span>
          </div> */}
          <div>
            <span className="w-120px inline-block ">文件名称：</span>
            <span className="inline-flex">
              <TextTooltip className="w-520px">{details?.fileName}</TextTooltip>{' '}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">文件路径：</span>
            <span className="inline-flex">
              <TextTooltip className="w-520px">{details?.filePath}</TextTooltip>
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">设备快照名称：</span>
            <span className="inline-flex">
              <TextTooltip className="w-520px">{details?.imgName}</TextTooltip>{' '}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">设备快照路径：</span>
            <span className="inline-flex">
              <TextTooltip className="w-520px">{details?.imgPath}</TextTooltip>
            </span>
          </div>

          <div>
            <span className="w-120px inline-block ">创建时间：</span>
            <span>
              {moment(details?.createTime).format('YYYY-MM-DD HH:mm:ss')}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">创建人：</span>
            <span>{details?.creatorName}</span>
          </div>
          <div>
            <span className="w-120px inline-block ">更新时间：</span>
            <span>
              {details?.updateTime
                ? moment(details?.updateTime).format('YYYY-MM-DD HH:mm:ss')
                : ''}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">更新人：</span>
            <span>{details?.updateName}</span>
          </div>
          <div className="text-#fff text-22px mt-20px equip-set">
            设备参数集合
          </div>
          <div className="border-b-1px flex border-#0c698b h-40px equip-set">
            <span className="w-33% flex items-center justify-center h-40px border-#0c698b border-x-1px">
              参数名称
            </span>
            <span className="w-33% flex items-center justify-center h-40px border-#0c698b border-r-1px">
              参数值
            </span>
            <span className="w-33.9% flex items-center justify-center h-40px border-#0c698b border-r-1px">
              参数描述
            </span>
          </div>
          {(details?.equipParams || []).map((equip: any, index: number) => {
            return (
              <div
                key={index}
                className="border-b-1px flex border-#0c698b h-40px equip-set"
              >
                <span className="w-33% flex items-center justify-center h-40px border-#0c698b border-x-1px">
                  {equip.paramName}
                </span>
                <span className="w-33% flex items-center justify-center h-40px border-#0c698b border-x-1px">
                  {equip.paramValue}
                </span>
                <span className="w-33.9% flex items-center justify-center h-40px border-#0c698b border-x-1px">
                  {equip.description}
                </span>
              </div>
            )
          })}
        </div>
      </Modal>
      <Modal
        width={800}
        title={details ? '编辑设备资料' : '上传设备资料'}
        visible={isModalOpen}
        onOk={() => {
          if (details) {
            addForm.validateFields().then((values) => {
              runUpdateEquip({
                ...details,
                ...values
              })
            })
          } else {
            addForm.validateFields().then((values) => {
              const formData = new FormData()
              formData.append('equipFile', values.equipFile.file)
              formData.append('equipImg', values.equipImg.file)
              // formData.append('description', values.description)
              formData.append('equipName', values.equipName)
              runCreateEquip(formData)
            })
          }
        }}
        onCancel={() => {
          setIsModalOpen(false)
          addForm.resetFields()
          setDetails(undefined)
        }}
      >
        <div className="h-400px overflow-auto">
          <Form
            name="register"
            initialValues={{
              prefix: '86'
            }}
            form={addForm}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Form.Item
              name="equipName"
              label="设备名称"
              rules={[{ required: true, message: '请输入标题' }]}
            >
              <Input></Input>
            </Form.Item>
            {/* <Form.Item
              name="description"
              label="摘要"
              rules={[{ required: true, message: '请输入摘要' }]}
            >
              <TextArea rows={4}></TextArea>
            </Form.Item> */}
            {!details ? (
              <>
                <Form.Item
                  name="equipFile"
                  label="文件"
                  rules={[{ required: true, message: '请上传文件' }]}
                >
                  <Upload
                    className="basis-upload"
                    beforeUpload={() => false}
                    accept=".ned"
                    headers={{
                      authorization: 'authorization-text'
                    }}
                  >
                    <Button icon={<UploadOutlined />}>上传</Button>
                  </Upload>
                </Form.Item>
                <Form.Item
                  name="equipImg"
                  label="图片"
                  rules={[{ required: true, message: '请上传图片' }]}
                >
                  <Upload
                    className="basis-upload"
                    beforeUpload={() => false}
                    accept=".jpg,.png,.gif,.jpeg"
                    headers={{
                      authorization: 'authorization-text'
                    }}
                  >
                    <Button icon={<UploadOutlined />}>上传</Button>
                  </Upload>
                </Form.Item>
              </>
            ) : (
              <>
                <div className="text-#fff text-22px mb-10px">设备参数集合</div>
                <Form.List name="equipParams">
                  {(fields, { add, remove }) => (
                    <>
                      {fields.map(({ name }: any, index: number) => {
                        return (
                          <div
                            key={index}
                            className="flex p-10px border-#2878c8 border-1px mb-10px"
                          >
                            <div className="flex-1">
                              <Form.Item
                                name={[name, 'paramName']}
                                label="参数名称"
                                labelCol={{ span: 5 }}
                                rules={[
                                  {
                                    required: true,
                                    message: '请输入参数名称'
                                  }
                                ]}
                              >
                                <Input></Input>
                              </Form.Item>
                              <Form.Item
                                key={index}
                                labelCol={{ span: 5 }}
                                name={[name, 'paramValue']}
                                label="参数值"
                                rules={[
                                  { required: true, message: '请输入参数值' }
                                ]}
                              >
                                <Input></Input>
                              </Form.Item>
                              <Form.Item
                                className="mb-0px"
                                key={index}
                                labelCol={{ span: 5 }}
                                name={[name, 'description']}
                                label="参数描述"
                                rules={[
                                  { required: true, message: '请输入参数描述' }
                                ]}
                              >
                                <Input></Input>
                              </Form.Item>
                            </div>
                            <div className="w-12px mt-6px ml-6px">
                              <MinusCircleOutlined
                                onClick={() => remove(index)}
                              />
                            </div>
                          </div>
                        )
                      })}
                      <Form.Item>
                        <Button
                          type="primary"
                          className="w-750px"
                          onClick={() => add()}
                          icon={<PlusOutlined />}
                        >
                          添加设备参数
                        </Button>
                      </Form.Item>
                    </>
                  )}
                </Form.List>
              </>
            )}
          </Form>
        </div>
      </Modal>
    </>
  )
}

export default Equip
